package com.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.BorrowDotAction;
import com.bean.DotBean;
import com.exception.BorrowDotException;
import com.exception.DBException;
import com.exception.UserException;
import com.util.HandleInfo;
import com.util.Regex;
import com.util.StateInfo;

public class BorrowDotServlet extends HttpServlet
{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		
		response.setHeader("pragma", "no-cache");
		response.setHeader("cache-control", "no-cache");
		
		String option = request.getParameter("option");
		if ("check".equals(option))
		{
			String userID = request.getParameter("userID");
			if (null == userID || "" == userID || userID.length() != 8
					|| !Regex.checkUserID(userID))
			{
				HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
				return;
			}
			DotBean dotBean = new DotBean();
			dotBean.setUserID(userID);
			try
			{
				new BorrowDotAction().getUser(request, response, dotBean);
			}
			catch (DBException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
			catch (UserException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
			catch (BorrowDotException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
		}
		if("submit".equals(option))
		{
			String userID = request.getParameter("userID");
			String context = request.getParameter("context");

			DotBean dotBean = new DotBean();
			dotBean.setUserID(userID);
			dotBean.setContext(context);
			
			if (null == userID || "" == userID || userID.length() != 8
					|| !Regex.checkUserID(userID))
			{
				HandleInfo.ajax(response, StateInfo.INNER_CONFIRM_FAIL);
				return;
			}
			
			try
			{
				new BorrowDotAction().updateUserDot(request, response, dotBean);
			}
			catch (DBException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
			catch (BorrowDotException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
			catch (UserException e)
			{
				HandleInfo.ajax(response, e.getMessage());
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doGet(request, response);
	}

}
